﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Xml;

namespace Models
{
    public class CreateConfig
    {

        #region Properties
        string savePath = string.Empty;
        #endregion

        public bool CreatDoc(CCPaths paths)
        {
            savePath = String.Format("{0}\\server\\{1}.xml.config", paths.CCPath, paths.ProjectName);
            string configPath = paths.CCPath + "\\server\\ccnet.config";
            using (StreamReader sr = new StreamReader(configPath))
            {
                string s = sr.ReadToEnd();
                sr.Close();
                if (!s.Contains(paths.ProjectName + ".xml.config"))
                {
                    var broken = s.Split(new string[] { "\n" }, StringSplitOptions.None);
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < broken.Length; i++)
                        if (broken[i].Contains("]>"))
                        {
                            sb.Append(string.Format("    <!ENTITY {0} SYSTEM \"file:{0}.xml.config\">\r\n\t", paths.ProjectName));
                            sb.Append(broken[i].Replace("\r\t", "\r\n\t"));
                        }
                        else
                            if (broken[i].Contains("</cruisecontrol>"))
                            {
                                sb.Append(string.Format("    &{0};\r\n\t", paths.ProjectName));
                                sb.Append(broken[i].Replace("\r\t", "\r\n\t"));
                            }
                            else
                                sb.Append(broken[i] + "\n");
                    using (StreamWriter sw = new StreamWriter(configPath))
                    {
                        sw.Write(sb.ToString());
                        sw.Close();
                    }
                }
            }

            #region CreateXml
            XDocument doc = new XDocument(

                        new XElement("project", new XAttribute("name", paths.ProjectName), new XAttribute("queue", paths.Queue), new XAttribute("queuePriority", paths.QueuePriority),
                        new XElement("triggers", new XElement("intervalTrigger", new XAttribute("name", "Continuous"), new XAttribute("seconds", "30"), new XAttribute("buildCondition", "ifModificationExists")),
                        new XElement("scheduleTrigger", new XAttribute("time", "07:15"), new XAttribute("name", "Scheduled"), new XAttribute("buildCondition", "ForceBuild"))),
                        new XElement("webURL", String.Format(@"http://yourServerName:yourSeverPort/server/local/project/{0}/ViewProjectReport.aspx", paths.ProjectName)),
                        new XElement("workingDirectory", paths.ProjectDirectory),
                        new XElement("artifactDirectory", String.Format("{0}\\{1} Logs", paths.ProjectLogs, paths.ProjectName)),                        
                        new XElement("sourcecontrol", new XAttribute("type", "svn"),
                        new XElement("trunkUrl", "yourSvnUrl" + paths.ProjectName),
                        new XElement("workingDirectory", paths.ProjectDirectory),
                        new XElement("executable", @"yourSvnPath"),
                        new XElement("autoGetSource", "true"),
                        new XElement("timeout", new XAttribute("units", "minutes"), "2"),
                        new XElement("username","replicat"),
                        new XElement("password","xer0x4me_"),
                        new XElement("cleanCopy", "false")),
                        new XElement("tasks",
                        new XElement("msbuild",
                        new XElement("executable", @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe"),
                        new XElement("workingDirectory", paths.ProjectDirectory),
                        new XElement("buildArgs", "/p:Configuration=Debug"),
                        new XElement("timeout", "900"),
                        new XElement("logger", paths.CCPath + @"\server\Thoughtworks.CruiseControl.MsBuild.dll")),
                        new XElement("exec",
                        new XElement("executable", paths.FxCopExecutable),
                        new XElement("baseDirectory", paths.ProjectDirectory),
                        new XElement("buildArgs", string.Format("/p:\"{0}.FxCop\" /out:\"{1}\\{0} Logs\\FxCop-{0}.xml\" /gac", paths.ProjectName, paths.ProjectLogs)),
                        new XElement("buildTimeoutSeconds", "300")),
                        new XElement("nunit",
                        new XElement("path", paths.NunitExecutable),
                        new XElement("assemblies",paths.NunitAssemblies),
                        new XElement("excludedCategories",
                        new XElement("excludedCategory", "LocalOnly")))),
                        new XElement("publishers",
                        new XElement("merge",
                        new XElement("files",
                        new XElement("file", string.Format("{0}\\{1} Logs\\FxCop-{1}.xml", paths.ProjectLogs, paths.ProjectName)))),
                        new XElement("xmllogger", new XAttribute("logDir","yourLogsDirectory")),
                        new XElement("email",new XAttribute("includeDetails","TRUE"),new XAttribute("mailhostUsername","smtpUserName"),new XAttribute("mailhostPassword","smtpPassword"), new XAttribute("useSSL","FALSE"),
                        new XElement("from","yourFromEmail"),
                        new XElement("mailhost","yourSmtpServer"),
                        new XElement("users",
                        new XElement("user",new XAttribute("name","Developer"),new XAttribute("group","Change"),new XAttribute("address","yourGroupEmail"))),
                        new XElement("groups",
                        new XElement("group",new XAttribute("name","Change"),
                        new XElement("notifications",
                        new XElement("notificattionType","Failed"),
                        new XElement("notificationType","Fixed")))),
                        new XElement("converters",
                        new XElement("regexConverter",new XAttribute("find",@"http://yourServer/ccnet"),new XAttribute("replace", @"http://yourServerName:yourServerPort/Default.aspx")),
                        new XElement("regexConverter", new XAttribute("find", "$"), new XAttribute("replace", "@yourdomain.com"))),
                        new XElement("modifierNotificationTypes",
                        new XElement("NotificationType","Failed"),
                        new XElement("NotificationType","Fixed")),
                        new XElement("subjectSettings",
                        new XElement("subject",new XAttribute("buildResult","StillBroken"),new XAttribute("value","Build is still broken for ${CCNetProject}")))))));

            doc.Save(savePath);
            #endregion

            return File.Exists(savePath);

        }

    }
}

